
#include <iostream>
#include <memory>
#include <string>

// Step 1: 定义抽象处理者 (Handler)
class Logger {
protected:
    std::shared_ptr<Logger> nextLogger_; // 下一个处理者

public:
    virtual ~Logger() = default;

    // 设置下一个处理者
    void setNextLogger(std::shared_ptr<Logger> nextLogger) {
        nextLogger_ = nextLogger;
    }

    // 处理日志请求
    void logMessage(int level, const std::string& message) {
        if (canHandle(level)) {
            write(message);
        } else if (nextLogger_) {
            nextLogger_->logMessage(level, message);
        } else {
            std::cout << "No handler available for level " << level << std::endl;
        }
    }

protected:
    virtual bool canHandle(int level) const = 0; // 判断是否能处理该级别的日志
    virtual void write(const std::string& message) const = 0; // 具体写日志的方法
};

// Step 2: 定义具体处理者 (Concrete Handler)
class InfoLogger : public Logger {
protected:
    bool canHandle(int level) const override {
        return level == 1; // INFO 级别
    }

    void write(const std::string& message) const override {
        std::cout << "[INFO]: " << message << std::endl;
    }
};

class WarningLogger : public Logger {
protected:
    bool canHandle(int level) const override {
        return level == 2; // WARNING 级别
    }

    void write(const std::string& message) const override {
        std::cout << "[WARNING]: " << message << std::endl;
    }
};

class ErrorLogger : public Logger {
protected:
    bool canHandle(int level) const override {
        return level == 3; // ERROR 级别
    }

    void write(const std::string& message) const override {
        std::cout << "[ERROR]: " << message << std::endl;
    }
};

// Step 3: 客户端代码
int main() {
    // 创建具体处理者
    auto infoLogger = std::make_shared<InfoLogger>();
    auto warningLogger = std::make_shared<WarningLogger>();
    auto errorLogger = std::make_shared<ErrorLogger>();

    // 构建责任链
    infoLogger->setNextLogger(warningLogger);
    warningLogger->setNextLogger(errorLogger);

    // 测试日志处理
    std::cout << "Logging messages:\n";

    infoLogger->logMessage(1, "This is an info message.");
    infoLogger->logMessage(2, "This is a warning message.");
    infoLogger->logMessage(3, "This is an error message.");
    infoLogger->logMessage(4, "This level is not handled.");

    return 0;
}


